<template>
  <div>
    <div style="text-align: end; margin-bottom: 10px">
      <a-space>
        <a-button type="primary" @click="handleBindPrams">
          <template #icon>
            <icon-link />
          </template>
          绑定参数
        </a-button>
      </a-space>
    </div>
    <a-spin :loading="data.loading">
      <a-table :data="data.tableData" :columns="data.columns" :pagination="false">
        <template #index="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
        <template #alarmStatus="{ record }">
          <template v-if="record.alarmStatus === 1">
            <a-tag color="green">已启用</a-tag>
          </template>
          <template v-else>
            <a-tag color="red">已停用</a-tag>
          </template>
        </template>
        <template #action="{ record }">
          <a-space>
            <a-table-column title="操作">
              <template v-if="record.alarmStatus === 1">
                <a-button type="text" size="small" status="warning" @click="handleRun(record, false, getList)">
                  <template #icon>
                    <icon-stop />
                  </template>
                  停用
                </a-button>
              </template>
              <template v-else>
                <a-button type="text" size="small" status="success" @click="handleRun(record, true, getList)">
                  <template #icon>
                    <icon-play-arrow />
                  </template>
                  启用
                </a-button>
              </template>
            </a-table-column>
            <a-button type="text" size="small" @click="handleBindParamsUpdata(record)">
              <template #icon>
                <icon-edit />
              </template>
              修改
            </a-button>
            <a-button type="text" status="danger" size="small" @click="handleBindParamsDelete(record)">
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
      <a-pagination
        :total="data.pagination.total"
        :current="data.pagination.pageStart"
        :page-size="data.pagination.pageLength"
        @change="handlePageChange"
        @page-size-change="handlePageSizeChange"
        style="float: right; margin-right: 20px; margin-top: 20px; justify-content: end"
      ></a-pagination>
    </a-spin>
    <a-modal
      v-if="data.bindVisible"
      title="绑定参数"
      v-model:visible="data.bindVisible"
      width="700px"
      @before-ok="handleBindParamsOk"
    >
      <a-form :model="data.form" ref="formRef">
        <a-form-item label="模板" field="tempId" :rules="[{ required: true, message: '请选择模板' }]">
          <!-- <a-select v-model="data.form.templateName" placeholder="请选择">
            <a-option
              v-for="item in data.thresholdList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select> -->
          <div class="flex flex-col">
            <a-input-search
              style="border-radius: 15px; margin-bottom: 5px; width: 200px"
              placeholder="输入可筛选模板名称"
              size="small"
              v-model="tableSearch"
            />
            <a-table
              style="width: 100%"
              size="mini"
              :scroll="{
                maxHeight: '300px'
              }"
              :columns="columns"
              row-key="id"
              :data="data.thresholdList.filter((item) => item.name.indexOf(tableSearch) > -1)"
              :row-selection="rowSelection"
              @select="handleSelect"
              :selected-keys="data.selectedKeys"
              :pagination="false"
              align="center"
            >
            </a-table>
          </div>
        </a-form-item>
        <a-form-item label="参数">
          <a-select value-key="paramId" allow-search allow-clear placeholder="请选择" v-model="data.form.paramsInfo">
            <a-option v-for="item in paramsList" :key="item.paramId" :value="item" :label="item.paramName"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="总次数">
          <a-input v-model="data.form.allTimes" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="告警次数">
          <a-input v-model="data.form.triggerTimes" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="级别">
          <a-select v-model="data.form.alarmLevel" placeholder="请选择">
            <a-option :value="1">1</a-option>
            <a-option :value="2">2</a-option>
            <a-option :value="3">3</a-option>
            <a-option :value="4">4</a-option>
            <a-option :value="5">5</a-option>
            <a-option :value="6">6</a-option>
            <a-option :value="7">7</a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="正常值上限">
          <a-input v-model="data.form.upperLimit" placeholder="请输入"></a-input>
        </a-form-item>
        <a-form-item label="正常值下限">
          <a-input v-model="data.form.lowerLimit" placeholder="请输入"></a-input>
        </a-form-item>
        <template v-if="data.templateFlag === 2">
          <a-form-item label="生效模式">
            <!-- <a-select v-model="data.form.activeWorkMode" placeholder="请选择">
              <a-option>生效模式1</a-option>
              <a-option>生效模式2</a-option>
            </a-select> -->
            <a-input v-model="data.form.activeWorkMode" placeholder="请输入"></a-input>
          </a-form-item>
          <a-form-item label="失效模式">
            <!-- <a-select v-model="data.form.inactiveWorkMode" placeholder="请选择">
              <a-option>失效模式1</a-option>
              <a-option>失效模式2</a-option>
            </a-select> -->
            <a-input v-model="data.form.inactiveWorkMode" placeholder="请输入"></a-input>
          </a-form-item>
        </template>
        <template v-if="+data.templateFlag === 3">
          <template v-for="(item, index) in data.form.timeList" :key="index">
            <a-form-item label="生效时间">
              <a-radio-group v-model="data.form.timeList[index].state">
                <a-radio :value="1">生效</a-radio>
                <a-radio :value="0">不生效</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-range-picker v-model="data.form.timeList[index].time" show-time />
                <a-button type="primary" @click="addTime()">
                  <template #icon>
                    <icon-plus />
                  </template>
                </a-button>
                <a-button v-if="data.form.timeList.length > 1" @click="deleteTime(index)">
                  <template #icon>
                    <icon-minus />
                  </template>
                </a-button>
              </a-space>
            </a-form-item>
          </template>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import { ref, reactive, onMounted, watch } from 'vue'
import { apiHome } from '@/api'
import { handleRun } from './api/index'

const tableSearch = ref('')
const props = defineProps({
  deviceId: {
    type: String,
    default: ''
  },
  paramsList: {
    type: Array,
    default: () => []
  },
  currentSatellite: {
    type: Object,
    default: () => {}
  }
})

const rowSelection = {
  type: 'radio'
}

const columns = [
  {
    title: '告警名称',
    dataIndex: 'name'
  },
  {
    title: '门限等级',
    dataIndex: 'monitorLevel',
    render: ({ record }) => {
      return record.monitorLevel === 1 ? '一级' : record.monitorLevel === 2 ? '二级' : '三级'
    }
  },
  {
    title: '门限警告值',
    children: [
      {
        title: '上限',
        dataIndex: 'firstLevelMaxValue'
      },
      {
        title: '下限',
        dataIndex: 'firstLevelMinValue'
      }
    ]
  },
  {
    title: '判别模式',
    dataIndex: 'conditionSet',
    render: ({ record }) => {
      return record.conditionSet === 1 ? '仅门限判断' : record.conditionSet === 2 ? '工作模式判单' : '持续时间判断'
    }
  }
]

const data = reactive({
  loading: false,
  tableData: [],
  satelitesList: [],
  paramsList: [],
  columns: [
    {
      title: '序号',
      slotName: 'index',
      width: 60,
      customRender: ({ index }) => {
        return index + 1 + (data.pagination.pageStart - 1) * data.pagination.pageLength
      }
    },
    {
      title: '告警模板名称',
      dataIndex: 'tempName'
    },
    {
      title: '总次数',
      dataIndex: 'allTimes'
    },
    {
      title: '告警次数',
      dataIndex: 'triggerTimes'
    },
    {
      title: '级别',
      dataIndex: 'alarmLevel'
    },
    {
      title: '运行状态',
      dataIndex: 'alarmStatus',
      slotName: 'alarmStatus'
    },
    {
      title: '创建时间',
      dataIndex: 'createDate'
    },
    {
      title: '操作',
      slotName: 'action',
      width: 150
    }
  ],
  satelliteId: null,
  selectedKeys: [],
  pagination: {
    total: 0,
    pageStart: 1,
    pageLength: 10
  },
  bindVisible: false,
  form: {
    timeList: [
      {
        state: 1,
        time: [],
        startTime: '',
        endTime: ''
      }
    ]
  },
  thresholdList: [],
  templateFlag: 0
})
const formRef = ref(null)

const handleBindParamsUpdata = (record) => {
  apiHome.getBindingDetail(record.id).then((res) => {
    data.bindVisible = true
    data.form = res.data
    if (res.data.activeTimeList && res.data.activeTimeList.length > 0) {
      data.templateFlag = 3
      data.form.timeList = res.data.activeTimeList.map((item) => {
        return {
          state: item.state,
          startTime: item.startTime,
          endTime: item.endTime,
          time: [item.startTime, item.endTime]
        }
      })
    }

    if (data.form.activeWorkMode || data.form.inactiveWorkMode) {
      data.templateFlag = 2
    }
    data.selectedKeys = [res.data.tempId]
    data.form.tempId = res.data.tempId
    data.form.tempName = res.data.tempName
    data.form.paramsInfo = {
      ...res.data
    }
  })
}

const handleBindParamsDelete = (record) => {
  Modal.confirm({
    title: '提示',
    content: '确定要解除绑定吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      apiHome.unbindThresholdTemplate(record.id).then((res) => {
        if (res.code === 200) {
          Message.success('解绑成功')
          getList()
        }
      })
    }
  })
}

const handleBindPrams = () => {
  data.bindVisible = true
  data.templateFlag = 0
  data.selectedKeys = []
  data.form = {
    timeList: [
      {
        state: 1,
        time: [],
        startTime: '',
        endTime: ''
      }
    ]
  }
}

const addTime = () => {
  data.form.timeList.push({
    state: 1,
    time: [],
    startTime: '',
    endTime: ''
  })
}

const deleteTime = (index) => {
  data.form.timeList.splice(index, 1)
}

const handleSelect = (rowKeys, rowKey, record) => {
  console.log(rowKeys, 'rowKeys')
  console.log(rowKey, 'rowKey')
  console.log(record, 'record')
  data.selectedKeys = rowKeys

  data.form.tempId = rowKey
  data.form.tempName = record.name
  if (record.conditionSet === 1) {
    data.templateFlag = 1
  } else if (record.conditionSet === 2) {
    data.templateFlag = 2
  } else {
    data.templateFlag = 3
    data.form.timeList = [
      {
        state: 1,
        time: [],
        startTime: '',
        endTime: ''
      }
    ]
  }
}

const handleBindParamsOk = (done) => {
  formRef.value.validate().then((col) => {
    console.log(data.form, 'data.form')
    const {
      satCode,
      satId,
      satName,
      subsystemId,
      subsystemName,
      deviceCode,
      deviceId,
      deviceName,
      paramCode,
      paramId,
      paramName
    } = data.form.paramsInfo
    data.form = {
      ...data.form,
      satCode,
      satId,
      satName,
      subsystemId,
      subsystemName,
      deviceCode,
      deviceId,
      deviceName,
      paramCode,
      paramId,
      paramName
    }
    data.form.satelliteId = data.form.satId
    if (data.templateFlag === 3) {
      data.form.timeList = data.form.timeList.map((item) => {
        return {
          ...item,
          startTime: item.time[0],
          endTime: item.time[1]
        }
      })
    } else {
      delete data.form.timeList
    }

    if (data.templateFlag !== 2) {
      data.form.activeWorkMode = null
      data.form.inactiveWorkMode = null
    }
    if (!col) {
      const api = data.form.id ? apiHome.updateBinding : apiHome.bindThresholdTemplate
      api(data.form).then((res) => {
        if (res.code === 200) {
          Message.success('绑定成功')
          data.bindVisible = false
          getList()
        } else {
          Message.error('绑定失败')
        }
      })
      done(true)
    } else {
      done(false)
    }
  })
}

const getThresholdList = () => {
  apiHome
    .getThresholdPageList({
      pageNum: 1,
      pageSize: 100
    })
    .then((res) => {
      if (res.code === 200) {
        data.thresholdList = res.data.list
      }
    })
}

const handlePageChange = (page) => {
  data.pagination.pageStart = page
  getList()
}

const handlePageSizeChange = (size) => {
  data.pagination.pageLength = size
  getList()
}

watch(
  () => props.deviceId,
  () => {
    getList()
  }
)

const getList = () => {
  console.log(props.deviceId, 'props.deviceId')
  data.loading = true
  apiHome
    .getThresholdTemplate(Object.assign(data.pagination, { deviceId: props.deviceId }))
    .then((res) => {
      if (res.code === 200) {
        data.loading = false
        data.tableData = res.data.list
        data.pagination.total = +res.data.total
      } else {
        data.loading = false
      }
    })
    .finally(() => {
      data.loading = false
    })
}

onMounted(() => {
  getThresholdList()
  if (props.deviceId) {
    getList()
  }
})
</script>

<style scoped>
:deep(.arco-btn-size-small) {
  padding: 5px;
}
</style>
